package com.wejoy.video.middle.station.data.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码工具类
 * @author admin
 */
public class ValidCodeUtil {
    private final static  char[] CODE_SEQUENCE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    private final static int CODE_COUNT = 4;

    /**
     * 生成验证码图片
     * @param validCode
     * @return
     */
    public static BufferedImage generateImg(String validCode) {
        //图片的宽和高
        int imgWidth = CODE_COUNT * 20;
        int imgHeight = 30;

        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_BGR);
        drawImg(image, validCode, imgWidth , imgHeight);
        return image;
    }

    /**
     * 生成验证码
     * @return
     */
    public static String generateRandomCode() {
        Random rand = new Random();
        //记录验证码
        StringBuilder chapter = new StringBuilder();
        for (int i = 0; i < CODE_COUNT; i++) {
            //记录字符
            chapter.append(CODE_SEQUENCE[rand.nextInt(CODE_SEQUENCE.length)]);
        }
        return chapter.toString();
    }

    /**
     *  根据宽度、高度、和验证码的个数绘制验证码图片，并返回验证码的值
     * @param buffImg   BufferedImage对象
     * @param validCode 验证码
     * @param imgWidth  图片宽度
     * @param imgHeight 图片高度
     * @return  验证码的值
     */
    private static void drawImg(BufferedImage buffImg, String validCode, int imgWidth, int imgHeight) {
        Random rand = new Random();
        Graphics2D gd = buffImg.createGraphics();

        //填充矩形
        gd.setColor(Color.WHITE);
        gd.fillRect(0, 0, imgWidth, imgHeight);

        //设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, imgHeight - 5);
        gd.setFont(font);

        //绘制边框
        gd.setColor(Color.BLACK);
        gd.drawRect(0, 0, imgWidth - 1, imgHeight - 1);

        //绘制灰色干扰线
        gd.setColor(Color.GRAY);
        for (int i = 0, x, y, x1, y1; i < 30; i++) {
            x = rand.nextInt(imgWidth);
            y = rand.nextInt(imgHeight);
            x1 = rand.nextInt(12);
            y1 = rand.nextInt(12);
            gd.drawLine(x, y, x + x1, y + y1);
        }

        //int codeCount = 4,
        int codeX = 15, codeY = 25;

        //临时变量
        String item;

        for (int i = 0, red, green, blue; i < validCode.length(); i++) {
            item = String.valueOf(validCode.charAt(i));
            //随机选择字符颜色
            red = rand.nextInt(255);
            green = rand.nextInt(255);
            blue = rand.nextInt(255);
            gd.setColor(new Color(red, green, blue));

            //绘制字符
            gd.drawString(item, (i + 1) * codeX, codeY);
        }
    }


}
